package com.ncmmall.api.apis.mall;

import com.ncmmall.api.apis.service.Result;
import com.ncmmall.domain.business.advertis.Advertis;
import com.ncmmall.domain.business.advertis.QAdvertis;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.brand.GoodsBrand;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.news.News;
import com.ncmmall.domain.business.news.QNews;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * 首页接口
 */
@RestController
@RequestMapping(value = "/home")
@Slf4j
public class HomeApi {

    @Autowired
    private QueryChannelService queryChannelService;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 首页接口
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    @ResponseBody
    public Result index() {
        Result result = new Result();
        try {

            List<Advertis> banners = queryChannelService.findAll("select a from Advertis a where a.position = 1 and a.platformType = 1 and a.status = 2 order by a.rank desc ", Advertis.class);
            banners.forEach(banner -> banner.setImage(storeDomain + "/uploads/" + banner.getImage()));

            List<GoodsChannel> channels = queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(1).and(QGoodsChannel.goodsChannel.supplierRecommend.isTrue()).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class);
            channels.forEach(channel -> {
                channel.setIcon(storeDomain + "/uploads/" + channel.getIcon());
                channel.setChildren(null);
            });

            List<News> newses = queryChannelService.findAll(QNews.news.status.eq(2).and(QNews.news.recommend.eq(2)).and(QNews.news.platformType.eq(1)), News.class);
            newses.forEach(news -> news.setContent(null));

            Advertis bigAdverce = queryChannelService.findOne(QAdvertis.advertis.position.eq(2).and(QAdvertis.advertis.status.eq(2)).and(QAdvertis.advertis.platformType.eq(1)), Advertis.class);
            if (null != bigAdverce) {
                bigAdverce.setImage(storeDomain + "/uploads/" + bigAdverce.getImage());
            }

            List<Advertis> smallAdverces = queryChannelService.findAll(QAdvertis.advertis.position.eq(3).and(QAdvertis.advertis.status.eq(2)).and(QAdvertis.advertis.platformType.eq(1)), Advertis.class);
            smallAdverces.forEach(smallAdverce -> smallAdverce.setImage(storeDomain + "/uploads/" + smallAdverce.getImage()));

            List<Map<String, Object>> subjects = queryChannelService.selectAllMap("select id, name from mall_subject where status = 2  and platformType = 1  order by rank asc", Collections.emptyMap());

            for (Map<String, Object> subject : subjects) {

                List<Map<String, Object>> goodsList = queryChannelService.selectAllMap("select mg.id, mg.goodsNo, mg.name, mg.defaultImage, mg.defaultPrice, mg.marketPrice from mall_goods_subject mgs left join mall_goods mg on mgs.goods_id = mg.id where mg.status = 3 and mgs.subjectId = :subjectId and mgs.platformType=1 order by mgs.`rank` asc ", ImmutableMap.of("subjectId", subject.get("id")));
                goodsList.stream().filter(goods -> goods.get("defaultImage") != null).forEach(goods -> goods.put("defaultImage", storeDomain + "/uploads/" + goods.get("defaultImage")));

                subject.put("goodsSubjects", goodsList);
            }

            QueryPageRequest page = new QueryPageRequest().setPageNo(1).setPageSize(10);

            QueryPage<Map<String, Object>> recommendGoodsPage = queryChannelService.selectPageMap("select id, goodsNo, name, defaultImage, defaultPrice, marketPrice from mall_goods where recommendSupplier = true and isSupplier = 1 and status = 3 and marketingType = 0 order by recommendTime desc ", page);
            List<Map<String, Object>> recommendGoods = recommendGoodsPage.getResult();

            for (Map<String, Object> recommendGood : recommendGoods) {
                if (null != recommendGood.get("defaultImage")) {
                    recommendGood.put("defaultImage", storeDomain + "/uploads/" + recommendGood.get("defaultImage"));
                }
            }

            List<GoodsBrand> brands = queryChannelService.findAll("select b from GoodsBrand b where b.status = 3 and b.recommend = true ", GoodsBrand.class);
            for (GoodsBrand brand : brands) {
                brand.setLogo(storeDomain + "/uploads/" + brand.getLogo());
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("banners", banners);
            data.put("channels", channels);
            data.put("newses", newses);
            data.put("brands", brands);
            data.put("bigAdverce", bigAdverce);
            data.put("smallAdverces", smallAdverces);
            data.put("recommendGoods", recommendGoods);
            data.put("subjects", subjects);

            return result.ok().inject(data);

        } catch (Exception e) {

            log.error("[首页获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    /**
     * 推荐商品列表
     */
    @RequestMapping(value = "/recommends", method = RequestMethod.GET)
    @ResponseBody
    public Result goodsList(@RequestParam(defaultValue = "2") int pageNo, @RequestParam(defaultValue = "10") int pageSize) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
            Map<String, Object> map = new HashMap<>();

            String hql = "select g from Goods g where g.recommendSupplier = true and g.status = 3 order by g.createTime desc ";
            QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Goods.class);
            for (Goods goods : page.getResult()) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());
            }

            return result.ok().inject(page);

        } catch (Exception e) {
            log.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


}
